package com.allwees.bs.task.product;

import com.alibaba.fastjson.JSONObject;
import com.allwees.core.common.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ObjectCannedACL;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * @author Daniel
 * @version 1.0.0
 * @since 2020/11/19 11:12
 */
@Slf4j
public class S3Processor {
    private static final String URL_PATTERN = "https://%s/%s";

    private S3Client s3;

    private Region region;

    private String bucketName;

    /**
     * cdn.allwees.com
     * cdn-test.allwees.com
     */
    protected String domainName;

    void init(JSONObject json) {
        region = Region.of(json.getString("region"));
        bucketName = json.getString("bucket");
        domainName = json.getString("domain");
        s3 = initS3Client();
    }

    protected String putObject(String module, String userUuid, String photo, Date createdAt) {
        try {
            URL url = new URL(photo);
            byte[] bytes = getContent(url);
            if (bytes == null) {
                return null;
            }
            String path = url.getPath();
            String suffix = path.substring(path.lastIndexOf('/'));
            String date = DateUtil.formatDate(createdAt, "yyyyMMdd");
            String objectKey = module + "/" + userUuid + "/" + date + suffix;
            PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .contentType("image/png")
                    .key(objectKey)
                    .acl(ObjectCannedACL.PUBLIC_READ)
                    .build();
            s3.putObject(putObjectRequest, RequestBody.fromBytes(bytes));
            return String.format(URL_PATTERN, domainName, objectKey);
        } catch (MalformedURLException e) {
            log.error(">>>>>>>>>>MalformedURL:{}", photo);
        } catch (Exception e) {
            log.error("putObject error.", e);
        }
        return null;
    }

    private byte[] getContent(URL url) {
        try {
            return IOUtils.toByteArray(url);
        } catch (Exception e) {
            return null;
        }
    }

    private S3Client initS3Client() {
        AwsCredentials credentials = AwsBasicCredentials.create("AKIAIN3B42OZREJBKBGA", "bRFWRpS/4JIjNiJSJlUcKr8NUEbDhlGBkTixtFaG");
        return S3Client.builder()
                .credentialsProvider(StaticCredentialsProvider.create(credentials))
                .region(region)
                .build();
    }
}
